window.onload=function () {
    const E = window.wangEditor
    const editor = new E('#discuss');
    const text1 = $('#text1')
    // 监控变化，同步更新到 textarea
    editor.config.onchange = function (html) {
        text1.val(html)
    }
    editor.config.height = 50
    //只需要表情菜单
    editor.config.menus = ['emoticon']
    editor.config.showFullScreen = false
    editor.config.placeholder = '请输入一条友善的评论';
    editor.create();

    var args=new Object();
    //查询URL的get参数
    var query=location.search.substring(1);//获取查询串
    var pairs=query.split(",");//在逗号处断开
    for(var i=0;i<pairs.length;i++){
        var pos=pairs[i].indexOf('=');//查找name=value
        if(pos==-1){//如果没有找到就跳过
            continue;
        }
        var argname=pairs[i].substring(0,pos);//提取name
        var value=pairs[i].substring(pos+1);//提取value
        args[argname]=unescape(value);//存为属性
    }
    //获取发帖人的id
    var useredid = document.getElementById("userid").innerText;
    //点击图片放大这个委托事件
    // $("#post").on("click","img",function(){
    //     console.log("123");
    //     var  newDiv=document.createElement('div');
    //     newDiv.className='mark';
    //     post.appendChild(newDiv);
    //     var  newImg=document.createElement('img');
    //     newImg.className='pic';
    //     newImg.src=this.src;
    //     // newImg.src=this.childNodes[0].src;
    //     post.appendChild(newImg);
    //     var newSpan=document.createElement ("span");
    //     newSpan.className='newspan'
    //     newSpan.innerHTML='X';
    //     post.appendChild(newSpan);
    //     newSpan.onclick=function(){
    //         post.removeChild(newDiv);
    //         post.removeChild(newSpan);
    //         post.removeChild(newImg);
    //     }
    // });

    //判断是否是自己的帖子
    $.get('isMyPost.do',{pid:args.pid},function (back) {
        console.log(back);
        if (back!=true){
            document.getElementById("updateImg").style.display="none";
            document.getElementById("update").style.display="none";
        }
    });

    //获取当前时间
    function getCurrentTime(){
        let now= new Date();
        let _month = ( 10 > (now.getMonth()+1) ) ? '0' + (now.getMonth()+1) : now.getMonth()+1;
        let _day = ( 10 > now.getDate() ) ? '0' + now.getDate() : now.getDate();
        let _hour = ( 10 > now.getHours() ) ? '0' + now.getHours() : now.getHours();
        let _minute = ( 10 > now.getMinutes() ) ? '0' + now.getMinutes() : now.getMinutes();
        let _second = ( 10 > now.getSeconds() ) ? '0' + now.getSeconds() : now.getSeconds();
        return now.getFullYear() + '-' + _month + '-' + _day + ' ' + _hour + ':' + _minute + ':' + _second;
    }

    //获取当日日期
    function getCurrentDate(){
        let now= new Date();
        let _month = ( 10 > (now.getMonth()+1) ) ? '0' + (now.getMonth()+1) : now.getMonth()+1;
        let _day = ( 10 > now.getDate() ) ? '0' + now.getDate() : now.getDate();
        return now.getFullYear() + '-' + _month + '-' + _day;
    }

    //给点赞状态赋值
    var giveupStatus;
    if ($("#giveup")[0].src=="http://localhost:8080/images/editor/giveup1.png"){
        giveupStatus=1;
    }else if ($("#giveup")[0].src=="http://localhost:8080/images/editor/giveup2.png"){
        giveupStatus=2;
    }else {
        console.log("点赞图标路径有误！");
    }
    $("#giveup").click(function () {
        if(giveupStatus==1){//点赞
            $.ajax({
                type:"get",
                url:"giveupPost.do",
                dataType:"text",
                data:{pid:args.pid,useredid:useredid,ldate:getCurrentDate()},
                success:function(back){
                    if (back=="true"){
                        console.log("点赞成功");
                        //将点赞图片切换为黄色
                        $("#giveup").attr("src","../../images/editor/giveup2.png");
                        var giveupCon = document.getElementById("giveupCon").innerHTML;
                        document.getElementById("giveupCon").innerHTML=parseInt(giveupCon)+1;
                        giveupStatus=2;
                    }
                },
                error:function(){
                    console.log("点赞失败");
                }
            });
        }
        if (giveupStatus==2){//取消点赞
            $.ajax({
                type:"get",
                url:"deleteGiveup.do",
                dataType:"text",
                data:{pid:args.pid,useredid:useredid},
                success:function(back){
                    if (back=="true"){
                        console.log("取消点赞成功");
                        //将点赞图片切换为灰色
                        $("#giveup").attr("src","../../images/editor/giveup1.png");
                        var giveupCon = document.getElementById("giveupCon").innerHTML;
                        document.getElementById("giveupCon").innerHTML=parseInt(giveupCon)-1;
                        giveupStatus=1;
                    }
                },
                error:function(){
                    console.log("取消点赞失败");
                }
            });
        }
    });

    //给点赞状态赋值
    var collectStatus;
    if ($("#collect")[0].src=="http://localhost:8080/images/editor/collection1.png"){
        collectStatus=1;
    }else if ($("#collect")[0].src=="http://localhost:8080/images/editor/collection2.png"){
        collectStatus=2;
    }else {
        console.log("收藏图标路径有误！")
    }
    $("#collect").click(function () {
        if (collectStatus==1){//收藏
            $.ajax({
                type:"get",
                url:"collectPost.do",
                dataType:"text",
                data:{pid:args.pid,useredid:useredid,ldate:getCurrentDate()},
                success:function(back){
                    if (back=="true"){
                        console.log("收藏成功");
                        //将收藏图片切换为黄色的
                        $("#collect").attr("src","../../images/editor/collection2.png");
                        var collectCon = document.getElementById("collectCon").innerHTML;
                        document.getElementById("collectCon").innerHTML=parseInt(collectCon)+1;
                        collectStatus=2;
                    }
                },
                error:function(){
                    console.log("收藏失败");
                }
            });
        }
        if (collectStatus==2){//取消收藏
            $.ajax({
                type:"get",
                url:"deleteCollection.do",
                dataType:"text",
                data:{pid:args.pid,useredid:useredid},
                success:function(back){
                    if (back=="true"){
                        console.log("取消收藏成功");
                        //将收藏图片切换为黄色的
                        $("#collect").attr("src","../../images/editor/collection1.png");
                        var collectCon = document.getElementById("collectCon").innerHTML;
                        document.getElementById("collectCon").innerHTML=parseInt(collectCon)-1;
                        collectStatus=1;
                    }
                },
                error:function(){
                    console.log("取消收藏失败");
                }
            });
        }
    });

    //点击评论按钮实现本页面跳转,用jquery获取不好使
    var ele = document.getElementById("discuss");
    function heightToTop(ele){
        //ele为指定跳转到该位置的DOM节点
        let bridge = ele;
        let root = document.body;
        let height = 0;
        do{
            height += bridge.offsetTop;
            bridge = bridge.offsetParent;
        }while(bridge !== root)

        return height;
    }
    //评论按钮点击时,跳转效果（smooth、instant）
    $("#dcbtn").click(function(){
        window.scrollTo({
            top:heightToTop(ele),
            behavior:'smooth'
        });
    });
    //跳转页面到修改
    $("#update").click(function () {
        window.location.href='/html/editor/editPost.do?pid='+args.pid;
    });
    //发表评论（父）
    $("#submitDiscuss").click(function () {
        var comcontent = $("#text1").val();
        //发送给后端的数据包括，pid  text1的内容comcontent  评论时间comtime  comup和fatherid和useredid为0
        $.post('submitDiscuss.do',{pid:args.pid,comcontent:comcontent,comtime:getCurrentTime},function(back){
            if (back!=null){
                location.reload();
            }else {
                console.log("评论发送失败");
            }
        })
    });

    //弹窗
    function showmsg(){
        document.getElementById("showmsg").style.display = 'block';
        setTimeout(hiden_search,1000);
    }
    function hiden_search(){
        document.getElementById("showmsg").style.display='none';
    }

    //复制链接
    $('#buttonCopy').click( function () {
        var url=document.URL;//获取url
        var aux = document.createElement("input");
        aux.setAttribute("value", url);
        document.body.appendChild(aux);
        aux.select();
        document.execCommand("copy");
        document.body.removeChild(aux);
        document.getElementById("msg").innerHTML="链接复制成功!!!";
        showmsg();
    });

/************************************************************************/

    // 评论框
    var useredname;
    var fatherid;
    var useredid;
    var before_comid;
    var reply_comid;
    $(".reply_btn").click(function () {
        useredname = $(this).prev().text();
        fatherid = $(this).parents("table").find("#father_comid").text();
        useredid = $(this).next().text();
        reply_comid=$(this).parent("td").find(".reply_comid").text();
        if (before_comid!=reply_comid){
            $("#big_div").remove();
            $(this).parents("table").find(".reply_write").append(
                "<div id='big_div'>"+
                "<div id='discuss_tab' style='float:left;width: 720px'>"+"</div>"+
                "&nbsp;&nbsp;"+
                "<input type='button' id='reply_button'  value='发表评论' style='width: 92px;height: 92px; background-color: orchid;color: white;border-radius: 5px'>"+
                "</div>"
            );
            const editor_tab = new E('#discuss_tab');
            const text2 = $('#text2')
            // 监控变化，同步更新到 textarea
            editor_tab.config.onchange = function (html) {
                text2.val(html)
            }
            editor_tab.config.placeholder = '回复@'+useredname+':';//设置输入框默认值
            editor.config.onchangeTimeout = 500 // 用户无操作 500 ms后保存历史记录
            editor.config.historyMaxSize = 50//修改历史记录的步数。
            editor_tab.config.height = 50
            editor_tab.config.weight = 25
            //只需要表情菜单
            editor_tab.config.menus = ['emoticon']
            editor_tab.config.showFullScreen = false
            editor_tab.create();
            before_comid = reply_comid;

        }
        else if (before_comid==reply_comid){
            $("#big_div").remove();
            before_comid=0;
        }
    })

    //发送评论
    $(".reply_write").on("click","#reply_button",function (){
        var reply_content = $("#text2").val();
        console.log(reply_content);
        var pid = args.pid;
        var comtime = getCurrentTime();
        if (reply_content!=""){
            $.ajax({
                type:"get",
                url:"insertReply.do",
                dataType:"json",
                data:"pid="+pid+"&comtime="+comtime+"&comcontent="+reply_content+"&comup="+0+"&fatherid="+fatherid+"&useredid="+useredid,
                success:function(back){
                    if (back!=null){
                        location.reload();
                    }
                }
            })
        }
    })

    //点赞
    $(".com_up").click(function () {
        reply_comid = $(this).parent("td").find(".reply_comid").text();
        var comup_amount = $(this).next().text();
        if ($(this).find("#up_img")[0].src=="http://localhost:8080/images/editor/comup1.png"){//点赞
            $(this).find("#up_img").attr('src',"../../../images/editor/comup2.png");
            $.ajax({
                type:"get",
                url:"updatecomup.do",
                dataType:"json",
                data:"comid="+reply_comid,
                success:function(back){
                    if (back=="true"){
                        console.log("点赞成功");
                    }
                }
            });
            if (comup_amount=="赞"){
                $(this).next().text(1);
            }else {
                var new_comup_amount= parseInt(comup_amount)+1;
                $(this).next().text(new_comup_amount);
            }
        }
        else if ($(this).find("#up_img")[0].src=="http://localhost:8080/images/editor/comup2.png"){//取消点赞
            $(this).find("#up_img").attr('src',"../../../images/editor/comup1.png");
            $.ajax({
                type:"get",
                url:"deletecomup.do",
                dataType:"json",
                data:"comid="+reply_comid,
                success:function(back){
                    if (back=="true"){
                        console.log("点赞成功");
                    }
                }
            });
            if (comup_amount==1){
                $(this).next().text("赞");
            }else {
                var new_comup_amount= parseInt(comup_amount)-1;
                $(this).next().text(new_comup_amount);
            }
        }
    })
}